#include "iuModuleICMP.hpp"
#include <cstdio>
#include "iuPacketIP.hpp"
#include "iuPacketICMP.hpp"
#include "iuModuleIP.hpp"

/**
 * @brief Fonction appelee quand le module IP recoit un paquet de type ICMP.
 * Cette fonction va repondre aux Echo-Request, et va afficher un message
 * lors d'un Echo-Reply
 * @param packet le paquet IP recu
 * @param moduleIP le module IP ayant recu le paquet
 */
void iuModuleICMP::receivePacket(iuPacketIP &packet, iuModuleIP &moduleIP)
{
   iuPacketICMP *packetICMP, *replyICMP;
   iuPacketIP *replyIP;

   if (!(packetICMP = (iuPacketICMP *)packet.getData()))
      return;

   //Si le paquet est un "echo-request", on y repond
   if (packetICMP->getType() == ICMP_ECHO_REQUEST)
   {
      printf("ICMP: Echo-Request received: src: %s ttl=%d size=%d\n", packet.getSource().toString(), packet.getTTL(), packetICMP->getSize());

      replyICMP = new iuPacketICMP();
      replyICMP->setType(ICMP_ECHO_REPLY);
      replyICMP->setSize(packetICMP->getSize());

      replyIP = new iuPacketIP();
      replyIP->setDestination(packet.getSource());
      replyIP->setId(iuPacketIP::getNextId());
      replyIP->setProtocol(0x1);
      replyIP->setData(replyICMP);

      moduleIP.sendPacket(*replyIP);
   }

   //Si c'est un "echo-reply", on affiche simplement un message
   else if (packetICMP->getType() == ICMP_ECHO_REPLY)
   {
      printf("ICMP: Echo-Reply received: src: %s ttl=%d size=%d\n", packet.getSource().toString(), packet.getTTL(), packetICMP->getSize());
   }
}
